package com.terry.activity.controller.base;

import com.terry.activity.bean.EnrollModel;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.web.bind.WebDataBinder;

import java.beans.PropertyEditorSupport;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Create On 17/9/27.
 *
 * @author TerrySolar
 */
public class CustomWebDataBinder {


    public CustomWebDataBinder() {
    }

    public CustomWebDataBinder(WebDataBinder binder) {
        doubleBinding(binder);
        intBinding(binder);
        dateBinding(binder);
        stringBinding(binder);
    }

    /**
     * 双精度数据绑定
     */
    private void doubleBinding(WebDataBinder binder) {
        binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, true));
        binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
        binder.registerCustomEditor(float.class, new CustomNumberEditor(Float.class, true));
        binder.registerCustomEditor(double.class, new CustomNumberEditor(Double.class, true));
    }

    /**
     * 整形数据绑定
     */
    private void intBinding(WebDataBinder binder) {
        binder.registerCustomEditor(BigInteger.class, new CustomNumberEditor(BigInteger.class, true));
        binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true));
        binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true));
        binder.registerCustomEditor(int.class, new CustomNumberEditor(Integer.class, true));
        binder.registerCustomEditor(long.class, new CustomNumberEditor(Long.class, true));
    }

    /**
     * 日期数据绑定
     */
    private void dateBinding(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
    }


    /**
     * 字符串数据绑定
     */
    private void stringBinding(WebDataBinder binder) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });

    }

}
